package org.example.algorithm.linkedlist;

/**
 * 反转链表:
 * 给定单链表的头节点 head ，请反转链表，并返回反转后的链表的头节点。
 */
public class ReverseListSolution {
    public static void main(String[] args)
    {

    }

    //方法1：迭代
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode tempNode = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tempNode;
        }
        return pre;
    }

    //方法2：递归
    public ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList2(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }
}
